'use client';

// 添加全局类型声明以支持跨文件共享状态
declare global {
  interface Window {
    _currentDocumentContent: any;
    _hasUnsavedChanges: boolean;
  }
}

import React, { useEffect, useState, useRef, useMemo, useCallback } from 'react';
import { useEditor, EditorContent, Editor } from '@tiptap/react';
import StarterKit from '@tiptap/starter-kit';
// 正确导入Collaboration扩展
import Collaboration from '@tiptap/extension-collaboration';
// 正确导入CollaborationCursor扩展，如果类型定义不存在，则使用any类型
// @ts-ignore
import CollaborationCursor from '@tiptap/extension-collaboration-cursor';
import Document from '@tiptap/extension-document';
import Paragraph from '@tiptap/extension-paragraph';
import Text from '@tiptap/extension-text';
import { useSocket } from '@/hooks/use-socket';
import { useAuth } from '@/hooks/use-auth';
import { ErrorBoundary } from '@/components/ui/error-boundary';
import { withMemo } from '@/components/hoc/with-memo';
import { Button } from '@/components/ui/button';
import { 
  Bold, 
  Italic, 
  List, 
  ListOrdered, 
  AlignLeft, 
  AlignCenter, 
  AlignRight, 
  Heading, 
  Undo, 
  Redo,
  MessagesSquare,
  AlertCircle,
  Eye,
  Save
} from 'lucide-react';
import { useSession } from 'next-auth/react';
import { debounce, throttle } from 'lodash';
import { useLocalStorage } from '@/hooks/use-local-storage';

// 导入冲突解决组件
import { ConflictResolver } from '@/components/project/conflict-resolver';
// 导入协作状态组件
import { CollaborationStatus } from '@/components/project/collaboration-status';
// 导入建议组件
import { DocumentSuggestions } from '@/components/project/document-suggestions';
// 导入段落编辑指示器组件
import { BlockEditorIndicator } from '@/components/project/block-editor-indicator';
// 导入光标覆盖组件
import { CursorOverlay } from '@/components/editor/cursor-overlay';
// 导入权限级别类型
import { PermissionLevel, BlockEditData, CursorPositionData, DocumentUpdateData } from '@/types/socket';

// 协作者光标颜色
const CURSOR_COLORS = [
  '#5D8AA8', '#E32636', '#FFBF00', '#9966CC', '#A4C639', 
  '#CD9575', '#665D1E', '#915C83', '#841B2D', '#00FFFF'
];

// 在import部分添加新的组件和hooks
import { useAutoSave } from '@/hooks/use-auto-save';
import { AutoSaveIndicator } from '@/components/project/auto-save-indicator';

// 生成块级ID函数
const generateBlockId = () => `block-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;

// 自定义文档扩展，启用块级编辑
const CustomDocument = Document.extend({
  content: 'block+',
});

// 自定义段落扩展，添加块ID
const CustomParagraph = Paragraph.extend({
  addAttributes() {
    return {
      blockId: {
        default: () => generateBlockId(), // 自动生成块ID
        parseHTML: element => element.getAttribute('data-block-id'),
        renderHTML: attributes => {
          if (!attributes.blockId) {
            return {};
          }
          return {
            'data-block-id': attributes.blockId,
          };
        },
      },
    };
  },
});

// 添加缺失的UI组件
interface ToolbarButtonProps {
  onClick?: () => void;
  active?: boolean;
  disabled?: boolean;
  title?: string;
  children: React.ReactNode;
}

// 工具栏按钮组件
function ToolbarButton({ onClick, active, disabled, title, children }: ToolbarButtonProps) {
  return (
    <button
      type="button"
      onClick={onClick}
      disabled={disabled}
      title={title}
      className={`p-1.5 rounded-md transition-colors ${
        active ? 'bg-primary/20 text-primary' : 'hover:bg-muted'
      } ${disabled ? 'opacity-50 cursor-not-allowed' : ''}`}
    >
      {children}
    </button>
  );
}

// 协作者列表组件
function CollaboratorsList({ users = {} }) {
  return (
    <div className="flex -space-x-1 overflow-hidden">
      {Object.values(users).map((user: any) => (
        <div 
          key={user.id} 
          className="h-6 w-6 rounded-full bg-gray-200 flex items-center justify-center text-xs font-medium border-2"
          style={{ borderColor: user.color || '#888' }}
          title={user.name}
        >
          {user.name?.charAt(0).toUpperCase()}
        </div>
      ))}
    </div>
  );
}

// 权限标记组件
function PermissionBadge({ permission = 'viewer' }) {
  const labels: Record<string, string> = {
    'owner': '所有者',
    'admin': '管理员',
    'editor': '编辑者',
    'commenter': '评论者',
    'viewer': '查看者'
  };
  
  return (
    <div className="text-xs text-muted-foreground">
      {labels[permission] || '查看者'}
    </div>
  );
}

export interface CollaborativeEditorProps {
  documentId: string;
  projectId: string;
  initialContent?: any;
  readOnly?: boolean;
  placeholder?: string;
  className?: string;
  userPermission?: PermissionLevel;
  onSave?: (content: any) => Promise<void>;
}

function CollaborativeEditorComponent({
  documentId,
  projectId,
  initialContent,
  readOnly = false,
  placeholder = '开始编辑文档...',
  className = '',
  userPermission = 'editor',
  onSave
}: CollaborativeEditorProps) {
  const { user } = useAuth();
  const { 
    isConnected, 
    socket, 
    joinProject, 
    sendDocUpdate, 
    sendCursorPosition,
    sendBlockEdit,
    onDocUpdated,
    onCursorMoved,
    lockDocument,
    unlockDocument
  } = useSocket();
  
  const [collaborators, setCollaborators] = useState<{
    [key: string]: { 
      id: string; 
      name: string; 
      color: string; 
      position?: { index: number } 
    }
  }>({});
  
  // 添加冲突状态
  const [hasConflict, setHasConflict] = useState(false);
  const [conflictData, setConflictData] = useState<{
    localContent: any;
    remoteContent: any;
    remoteUser: { id: string; name: string };
    timestamp: number;
  } | null>(null);
  
  // 添加文档版本控制
  const [documentVersion, setDocumentVersion] = useState<number>(0);
  const lastSyncedVersion = useRef<number>(0);
  
  // 当前编辑的块ID
  const [currentBlockId, setCurrentBlockId] = useState<string | null>(null);
  // 活跃块编辑状态
  const [activeBlocks, setActiveBlocks] = useState<{
    [blockId: string]: {
      userId: string;
      userName: string;
      color: string;
      startedAt: number;
    }
  }>({});
  
  // eturn canEdit || canComment;
  }, [canEdit, canComment]);
  
  // 创建编辑器引用
  const editorRef = useRef<HTMLDivElement>(null);
  
  // 初始化编辑器
  const editor = useEditor({
    extensions: [
      StarterKit.configure({ document: false, paragraph: false }),
      CustomDocument,
      CustomParagraph,
      Text,
      Collaboration.configure({
        // 配置协作功能
        document: { 
          type: 'shared-doc', 
          name: documentId
        } as any
      }),
      CollaborationCursor.configure({
        // 配置协作光标
        provider: socket,
        user: user ? {
          name: user.name || 'Anonymous',
          color: CURSOR_COLORS[Math.floor(Math.random() * CURSOR_COLORS.length)],
        } : undefined,
      }),
    ],
    content: initialContent?.content || '',
    editable: canEdit,
    onUpdate: ({ editor }) => {
      // 编辑器内容更新时触发
      if (typeof window !== 'undefined') {
        window._hasUnsavedChanges = true;
      }
      // 存储当前内容引用
      contentRef.current = editor.getJSON();
    },
    editorProps: {
      handleClick: (view, pos, event) => {
        // 如果无法编辑，不处理点击
        if (!canEdit) return;
        
        try {
          // 检测是否点击了段落，并记录块编辑状态
          const node = view.state.doc.nodeAt(pos);
          if (node && node.type.name === 'paragraph') {
            const blockId = node.attrs.blockId;
            
            // 如果当前没有正在编辑的块，或者点击了不同的块
            if (blockId && currentBlockId !== blockId) {
              // 先停止编辑当前块
              if (currentBlockId) {
                stopEditingBlock(currentBlockId);
              }
              
              // 开始编辑新块
              startEditingBlock(blockId);
              setCurrentBlockId(blockId);
            }
          }
        } catch (error) {
          console.error("块编辑处理错误:", error);
        }
      }
    }
  });
  
  // 使用自动保存hook
  const {
    status: autoSaveStatus,
    lastSavedAt,
    triggerAutoSave,
    save: saveDocument,
    checkLocalBackup,
    clearLocalBackup,
    hasLocalBackup
  } = useAutoSave({
    projectId,
    documentId,
    initialContent,
    onSave,
    enabled: canEdit
  });
  
  // 初始化编辑器时设置初始版本
  useEffect(() => {
    if (initialContent && initialContent.version) {
      setDocumentVersion(initialContent.version);
      lastSyncedVersion.current = initialContent.version;
    }
  }, [initialContent]);
  
  // 将保存文档函数包装在useCallback中以避免循环依赖
  const saveDocumentCallback = useCallback(async () => {
    if (!editor || !canEdit) return;
    
    try {
      console.log('手动保存文档开始');
      const content = editor.getJSON();
      
      // 更新版本号
      const newVersion = documentVersion + 1;
      setDocumentVersion(newVersion);
      lastSyncedVersion.current = newVersion;
      
      // 保存到全局变量，供页面卸载事件使用
      if (typeof window !== 'undefined') {
        window._currentDocumentContent = content;
      }
      
      // 使用自动保存hook提供的保存函数
      await saveDocument({
        content,
        version: newVersion
      });
      
      console.log('手动保存文档成功');
      
      // 保存成功后清除本地备份和未保存标记
      clearLocalBackup();
      if (typeof window !== 'undefined') {
        window._hasUnsavedChanges = false;
      }
      
    } catch (error) {
      console.error('保存文档失败:', error);
      // 保存失败时，保留本地备份
    }
  }, [editor, canEdit, documentVersion, saveDocument, clearLocalBackup]);
  
  // 自动保存到服务器函数 - 使用节流以减少请求频率
  const autoSaveToServer = useCallback(throttle(async () => {
    if (!editor || !canEdit || !user) return;
    
    try {
      console.log('自动保存被触发', { documentId, projectId });
      const content = editor.getJSON();
      
      // 保存到全局变量，供页面卸载事件使用
      if (typeof window !== 'undefined') {
        window._currentDocumentContent = content;
        // 根据自动保存状态更新未保存更改标志
        window._hasUnsavedChanges = autoSaveStatus !== 'saved' && autoSaveStatus !== 'manually_saved';
      }
      
      // 确保内容存在且不为空
      if (!content || Object.keys(content).length === 0) {
        console.warn('自动保存: 内容为空，跳过保存');
        return;
      }
      
      // 在保存前记录到本地存储作为备份
      const localBackupKey = `doc_backup_${projectId}_${documentId}`;
      try {
        localStorage.setItem(localBackupKey, JSON.stringify({
          content,
          timestamp: Date.now(),
          userId: user.id,
          version: documentVersion
        }));
        console.log('自动保存: 已创建本地备份');
      } catch (e) {
        console.error('自动保存: 创建本地备份失败', e);
      }
      
      // 使用自动保存hook提供的触发函数
      triggerAutoSave(content);
    } catch (error) {
      console.error('自动保存到服务器失败:', error);
    }
  }, 1500), [editor, canEdit, user, triggerAutoSave, autoSaveStatus, documentId, projectId, documentVersion]);
  
  // 监听编辑器变化以触发自动保存
  useEffect(() => {
    if (!editor || !canEdit) return;
    
    const updateListener = () => {
      // 标记有未保存的更改
      if (typeof window !== 'undefined') {
        window._hasUnsavedChanges = true;
      }
      
      // 触发自动保存
      autoSaveToServer();
    };
    
    // 监听编辑器内容变化
    editor.on('update', updateListener);
    
    return () => {
      editor.off('update', updateListener);
      // 取消任何未处理的节流函数
      if (autoSaveToServer.cancel) {
        autoSaveToServer.cancel();
      }
    };
  }, [editor, canEdit, autoSaveToServer]);
  
  // 加入项目及监听协作事件
  useEffect(() => {
    if (!isConnected || !socket || !user) return;
    
    // 加入项目
    joinProject(projectId);
    
    // 监听用户加入项目
    const handleUserJoined = (data: any) => {
      if (data.projectId !== projectId) return;
      
      setCollaborators(prev => ({
        ...prev,
        [data.user.id]: {
          id: data.user.id,
          name: data.user.name,
          color: data.user.color || CURSOR_COLORS[Math.floor(Math.random() * CURSOR_COLORS.length)],
          lastActive: new Date()
        }
      }));
    };
    
    // 监听用户离开
    const handleUserLeft = (data: any) => {
      if (data.projectId !== projectId) return;
      
      setCollaborators(prev => {
        const newCollaborators = { ...prev };
        delete newCollaborators[data.user.id];
        return newCollaborators;
      });
      
      // 清除该用户正在编辑的块
      setActiveBlocks(prev => {
        const newBlocks = { ...prev };
        Object.keys(newBlocks).forEach(blockId => {
          if (newBlocks[blockId].userId === data.user.id) {
            delete newBlocks[blockId];
          }
        });
        return newBlocks;
      });
    };
    
    // 监听块编辑状态
    const handleBlockEditing = (data: BlockEditData) => {
      if (data.projectId !== projectId || data.docId !== documentId) return;
      
      if (data.isEditing) {
        setActiveBlocks(prev => ({
          ...prev,
          [data.blockId]: {
            userId: data.userId,
            userName: data.userName,
            color: data.userColor || '#888',
            startedAt: Date.now()
          }
        }));
      } else {
        setActiveBlocks(prev => {
          const newBlocks = { ...prev };
          if (newBlocks[data.blockId]?.userId === data.userId) {
            delete newBlocks[data.blockId];
          }
          return newBlocks;
        });
      }
    };
    
    // 直接添加事件监听，而不是使用socket.on
    if (socket) {
      socket.on('member-joined', handleUserJoined);
      socket.on('member-left', handleUserLeft);
      socket.on('block-editing', handleBlockEditing);
    }
    
    return () => {
      // 清理事件监听
      if (socket) {
        socket.off('member-joined', handleUserJoined);
        socket.off('member-left', handleUserLeft);
        socket.off('block-editing', handleBlockEditing);
      }
    };
  }, [isConnected, socket, projectId, documentId, user, joinProject]);
  
  // 处理冲突解决
  const handleResolveConflict = useCallback((resolution: any) => {
    if (!editor) return;
    
    // 使用选择的解决方案更新编辑器内容
    if (resolution === 'local') {
      // 使用本地内容
      if (conflictData?.localContent) {
        editor.commands.setContent(conflictData.localContent);
      }
    } else if (resolution === 'remote') {
      // 使用远程内容
      if (conflictData?.remoteContent) {
        editor.commands.setContent(conflictData.remoteContent);
      }
    } else if (resolution === 'merge') {
      // 合并内容 (简单示例，实际合并逻辑会更复杂)
      if (conflictData?.remoteContent) {
        editor.commands.setContent(conflictData.remoteContent);
        // 在这里可以添加更复杂的内容合并逻辑
      }
    }
    
    // 重置冲突状态
    setHasConflict(false);
    setConflictData(null);
    
    // 触发保存
    autoSaveToServer();
  }, [editor, conflictData, autoSaveToServer]);
  
  // 开始编辑块
  const startEditingBlock = useCallback((blockId: string) => {
    if (!isConnected || !socket || !user) return;
    
    // 通知其他用户
    sendBlockEdit({
      projectId,
      docId: documentId,
      blockId,
      userId: user.id,
      userName: user.name || 'Anonymous',
      userColor: CURSOR_COLORS[Math.floor(Math.random() * CURSOR_COLORS.length)],
      isEditing: true,
      timestamp: Date.now() // 添加缺失的timestamp字段
    });
    
    // 本地立即更新UI
    setActiveBlocks(prev => ({
      ...prev,
      [blockId]: {
        userId: user.id,
        userName: user.name || 'Anonymous',
        color: CURSOR_COLORS[Math.floor(Math.random() * CURSOR_COLORS.length)],
        startedAt: Date.now()
      }
    }));
  }, [isConnected, socket, user, documentId, projectId, sendBlockEdit]);
  
  // 停止编辑块
  const stopEditingBlock = useCallback((blockId: string) => {
    if (!isConnected || !socket || !user) return;
    
    // 通知其他用户
    sendBlockEdit({
      projectId,
      docId: documentId,
      blockId,
      userId: user.id,
      userName: user.name || 'Anonymous', // 添加必需的userName字段
      isEditing: false,
      timestamp: Date.now() // 添加缺失的timestamp字段
    });
    
    // 本地立即更新UI
    setActiveBlocks(prev => {
      const newBlocks = { ...prev };
      if (newBlocks[blockId]?.userId === user.id) {
        delete newBlocks[blockId];
      }
      return newBlocks;
    });
    
    // 清除当前编辑块
    if (currentBlockId === blockId) {
      setCurrentBlockId(null);
    }
  }, [isConnected, socket, user, currentBlockId, documentId, projectId, sendBlockEdit]);
  
  // 在页面卸载前停止编辑所有块
  useEffect(() => {
    return () => {
      // 如果有当前编辑的块，停止编辑
      if (currentBlockId) {
        stopEditingBlock(currentBlockId);
      }
    };
  }, [currentBlockId, stopEditingBlock]);
  
  // 渲染块编辑指示器
  const renderBlockIndicators = useCallback(() => {
    if (!editorRef.current || !ur
    
    return Array.from(blockElements).map(element => {
      const blockId = element.getAttribute('data-block-id');
      if (!blockId) return null;
      
      const editorckId] || [];
      const hdidorstors = editorsEditor.filter(ed || []itor => editor.userId !== user.id);
      otherEodiiorsor.filt(edior Editor=> editor! || [])
      if (ototherEdhtoretoreditor..filtle(editor => editor === 0) !reurn nll;)
      if (otherEditors.length === 0) return null;
      if (otherEditors.length === 0) return null;
      
      视觉
      const r视ct = e觉geBounClenRct(
      co c  ed 视orR觉co = ClenRcRf.curen!gtBouningClientRect(
      
      // 为正在编辑的块添加样式
      co c  edclaesLBs .adddiblocktbfcng-tdiied'
      
      // 为正边框颜色（使用第一个编辑者的颜色）辑的块添加样式
      const primarcColorisLsdhorbdi.orn[0].ustrColor;
      emen.sAtribut('syle',
      //bor为er颜（eft: 3px s使l个编 的颜primaryCo）辑r样;
    elemenprimarcColorssLt0]p)imlryC
    emenpadtingbut('sy12e'
    //bom设rg颜（ft: 3px-15s使l个编 的颜primaryCo）r;
  const primaryColor = s0]peimlryC;
      `);
  elemad.ingtAttrib12te
      return (mdrg-lft: 3px-15solid ${primaryColor};
        <biv
          key={blackId}
          classNag-="obsolut  z-10"
          yColo={{10;
           dtlp: reet.top - e: 12pRet.p - 8,
            left: -200,
            width: 180
          }}
        >margin-left: -15px;
          < iv
            plassNas:="lbsoluti z-10"
            ={{
             tp: ret.top - eRet.p - 8,
            onA tiveEditorfCh:ng-={(count) 2> {
              // 可以在这里处理编辑者数量变化
              con.log(`块${bockId} 有 ${coun} 个编辑者`);
            }}
         />
        < div   width: 180
          }}
        >
          <divEditor
            className="absolute z-10"
            style={{
              top: rect.top - editorRect.top - 8,
            onA tiveEditorfCh:ng-={(count) 2> {
              // 可以在这里处理编辑者数量变化
              con.log(`块${bockId} 有 ${coun} 个编辑者`);
            }}
         />
        < div   width: 180
          }}
        >
          <BlockEEditorditorIndicator
            projectId={projectId}
            documentId={documentId}
            blockId={blockId}
            onActiveEditorsChange={(count) => {
              // 可以在这里处理编辑者数量变化
              console.log(`块 ${blockId} 有 ${count} 个编辑者`);
            }}
          />
        </div>
      );
    });
  }, [activeBlockEditors, user, projectId, documentId, editorRef]);
  
  // 在工具栏中添加保存按钮
  return (
    <ErrorBoundary>
      <div className={`collaborative-editor-container ${className}`}>
        {showToolbar && (
          <div className="editor-toolbar flex items-center justify-between border-b p-2 bg-background">
            <div className="flex items-center space-x-1">
              {/* 工具栏按钮 */}
              <ToolbarButton 
                onClick={() => editor?.chain().focus().toggleBold().run()}
                active={editor?.isActive('bold') || false}
                disabled={!canEdit}
                title="加粗"
              >
                <Bold className="h-4 w-4" />
              </ToolbarButton>
              {/* ... 其他工具栏按钮 ... */}
                
              {/* 添加保存按钮 */}
              {canEdit && (
                <ToolbarButton 
                  onClick={saveDocumentCallback}
                  disabled={autoSaveStatus === 'saving'}
                  title="保存文档"
                >
                  <Save className="h-4 w-4" />
                </ToolbarButton>
              )}
                
              {/* 删除重复的保存按钮 */}
            </div>
            
            {/* 添加自动保存状态指示器 */}
            <div className="flex items-center space-x-2">
              <AutoSaveIndicator 
                status={autoSaveStatus} 
                lastSavedAt={lastSavedAt} 
              />
              <CollaboratorsList users={collaborators} />
              <PermissionBadge permission={userPermission} />
            </div>
          </div>
        )}
      
        {/* 编辑器内容 */}
        <div className="relative" ref={editorRef}>
          <EditorContent 
            editor={editor} 
            className={`p-4 min-h-[200px] prose-sm focus:outline-none ${
              !canEdit ? 'cursor-default select-text' : ''
            }`} 
          />
          
          {/* 添加光标覆盖层 */}
          {editorRef.current && isConnected && user && (
            <CursorOverlay 
              editorRef={editorRef} 
              documentId={documentId} 
            />
          )}
          
          {/* 如果不能编辑，显示只读遮罩 */}
          {!canEdit && !canComment && (
            <div className="absolute top-2 right-2 bg-gray-200 text-gray-600 rounded-md px-2 py-1 text-xs flex items-center opacity-70">
              <Eye className="h-3 w-3 mr-1" />
              只读模式
            </div>
          )}
          
          {/* 渲染块编辑指示器 */}
          {renderBlockIndicators()}
        </div>
        
        {/* 状态栏 */}
        <div className="flex items-center justify-between border-t p-1 text-xs text-muted-foreground">
          <div>
            {Object.keys(collaborators).length > 0 && (
              <span>{Object.keys(collaborators).length} 人正在查看</span>
            )}
          </div>
          <div className="flex items-center gap-2">
            {/* 自动保存状态指示器 */}
            <div className="flex items-center">
              {autoSaveStatus === 'saving' && (
                <span className="flex items-center">
                  <svg className="animate-spin -ml-1 mr-2 h-3 w-3 text-muted-foreground" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                  </svg>
                  自动保存中...
                </span>
              )}
              {autoSaveStatus === 'saved' && (
                <span className="flex items-center text-green-600">
                  <svg className="h-3 w-3 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M5 13l4 4L19 7"></path>
                  </svg>
                  已自动保存
                </span>
              )}
              {autoSaveStatus === 'manually_saved' && (
                <span className="flex items-center text-blue-600">
                  <svg className="h-3 w-3 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M17 3H7c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-1 16H8c-.55 0-1-.45-1-1V6c0-.55.45-1 1-1h8c.55 0 1 .45 1 1v12c0 .55-.45 1-1 1z"></path>
                  </svg>
                  已手动保存
                </span>
              )}
              {autoSaveStatus === 'error' && (
                <span className="flex items-center text-red-600">
                  <svg className="h-3 w-3 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path>
                  </svg>
                  自动保存失败
                </span>
              )}
            </div>
            
            {lastSavedAt && (
              <span>
                上次保存: {lastSavedAt.toLocaleTimeString()}
              </span>
            )}
          </div>
        </div>
        
        {/* 添加样式 */}
        <style jsx global>{`
          .collaborative-editor-container {
            display: flex;
            flex-direction: column;
            height: 100%;
            border-radius: 8px;
            background: white;
          }
          
          .collaborative-editor-container .ProseMirror {
            min-height: 300px;
            padding: 1rem;
            outline: none;
          }
          
          .collaborative-editor-container .ProseMirror p {
            margin: 0.75em 0;
            position: relative;
            transition: background-color 0.2s, padding-left 0.2s;
          }
          
          .collaborative-editor-container .ProseMirror p:hover {
            background-color: #f9f9f9;
          }
          
          .being-edited {
            border-radius: 4px;
            transition: all 0.3s ease;
          }
          
          .cursor-blink {
            animation: cursor-blink-animation 1.5s ease-in-out infinite;
          }
          
          @keyframes cursor-blink-animation {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.4; }
          }
        `}</style>
        
        {/* 冲突解决对话框 */}
        {hasConflict && conflictData && (
          <ConflictResolver
            isOpen={hasConflict}
            onClose={() => setHasConflict(false)}
            localContent={conflictData.localContent}
            remoteContent={conflictData.remoteContent}
            remoteUser={conflictData.remoteUser}
            timestamp={conflictData.timestamp}
            onResolve={handleResolveConflict}
          />
        )}
      </div>
    </ErrorBoundary>
  );
}

// 带错误边界的协作编辑器组件
export function CollaborativeEditor(props: CollaborativeEditorProps) {
  return (
    <ErrorBoundary>
      <CollaborativeEditorComponent {...props} />
    </ErrorBoundary>
  );
} 
